﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using Entity;

namespace SalesVMT
{
    public partial class frmShipment : Form
    {
        DialogResult dlgResult;
        ShipmentInfo Shipmentinf;
        public frmShipment(int _Shipment_ID)
        {
            InitializeComponent();
            Shipmentinf = new ShipmentInfo();
            lblNo.Text = UISetting.AutoFillShipmentCode();
            mtxShipmentDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            cboForms.SelectedIndex = 0;
            DisplayFrame();
            Shipmentinf.Shipment_ID = _Shipment_ID;
            if (_Shipment_ID > 0)
            {
                Shipmentinf = ShipmentDB.GetInfo(_Shipment_ID);
                
                InfoToForm();
                LoadList();
            }
            
            TotalRowsPrice();
            this.KeyPreview = true;
            dlgResult = DialogResult.Cancel;
            
        }
        private void FormToInfo()
        {
            Shipmentinf.Shipment_Code = lblNo.Text;
            Shipmentinf.Shipment_Date = DateTime.ParseExact(mtxShipmentDate.Text, "dd/MM/yyyy", null);
            Shipmentinf.Shipment_Forms = cboForms.Text;
            Shipmentinf.Shipment_CustomerID = Convert.ToInt32(lblCustomer.Tag);
            Shipmentinf.Shipment_Receive = txtReceive.Text;
            Shipmentinf.Shipment_UsersID = UsersDB.GetInfoByUsersName(Program.strUserName).Users_ID;
            Shipmentinf.Shipment_TotalPrice = Convert.ToDecimal(txtTotalPrice.Text);
            Shipmentinf.Shipment_TotalDownPrice = Convert.ToDecimal(txtTotalDownPrice.Text);
            Shipmentinf.Shipment_TotalVAT = Convert.ToDecimal(txtTotalVAT.Text);
            Shipmentinf.Shipment_Total = Convert.ToDecimal(txtTotal.Text);
            Shipmentinf.Shipment_Remaining = Convert.ToDecimal(txtRemaining.Text);
        }
        private void InfoToForm()
        {
            lblNo.Text = Shipmentinf.Shipment_Code;
            mtxShipmentDate.Text = Convert.ToDateTime(Shipmentinf.Shipment_Date).ToString("dd/MM/yyyy");
            cboForms.Text = Shipmentinf.Shipment_Forms;
            lblCustomer.Tag = Shipmentinf.Shipment_CustomerID;
            lblCustomer.Text = CustomerDB.GetInfo(Convert.ToInt32(lblCustomer.Tag)).Customer_Name;
            txtReceive.Text = Shipmentinf.Shipment_Receive;
            txtRemaining.Text = Convert.ToDecimal(Shipmentinf.Shipment_Remaining).ToString("N1");
        }
        private void LoadList()
        {
            DataTable _dt = ShipmentDetailsDB.GetAllByShipment(Shipmentinf.Shipment_ID).Tables[0];
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList1.Rows.Insert(i, 1);
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList1.Rows[i].Cells["Item_ID"].Value = _dt.Rows[i]["Item_ID"].ToString();
                dgvList1.Rows[i].Cells["Item_Code"].Value = _dt.Rows[i]["Item_Code"].ToString();
                dgvList1.Rows[i].Cells["Item_Name"].Value = _dt.Rows[i]["Item_Name"].ToString();
                dgvList1.Rows[i].Cells["CalculationUnit_Name"].Value = _dt.Rows[i]["CalculationUnit_Name"].ToString();
                dgvList1.Rows[i].Cells["Quantity"].Value = _dt.Rows[i]["ShipmentDetails_Quantity"].ToString();
                dgvList1.Rows[i].Cells["Price"].Value = Convert.ToDecimal(_dt.Rows[i]["ShipmentDetails_Price"]).ToString("N1");
                dgvList1.Rows[i].Cells["DownPrice"].Value = Convert.ToDecimal(_dt.Rows[i]["ShipmentDetails_DownPrice"]).ToString("N1");
                dgvList1.Rows[i].Cells["VAT"].Value = Convert.ToInt32(_dt.Rows[i]["ShipmentDetails_VAT"]);
                dgvList1.Rows[i].Cells["Total"].Value = Convert.ToDecimal(_dt.Rows[i]["ShipmentDetails_Total"]).ToString("N1");
            }
        }

        private ShipmentDetailsInfo[] ReadShipmentDetails()
        {
            int n = dgvList1.Rows.Count;
            if (n > 0)
            {
                ShipmentDetailsInfo[] tracks = new ShipmentDetailsInfo[n];
                for (int i = 0; i < n; i++)
                {
                    tracks[i] = new ShipmentDetailsInfo();
                    tracks[i].ShipmentDetails_ItemID = Convert.ToInt32(dgvList1.Rows[i].Cells["Item_ID"].Value);
                    tracks[i].ShipmentDetails_Quantity = Convert.ToInt32(dgvList1.Rows[i].Cells["Quantity"].Value);
                    tracks[i].ShipmentDetails_Price = Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value);
                    tracks[i].ShipmentDetails_DownPrice = Convert.ToDecimal(dgvList1.Rows[i].Cells["DownPrice"].Value);
                    tracks[i].ShipmentDetails_VAT = Convert.ToInt32(dgvList1.Rows[i].Cells["VAT"].Value);
                    tracks[i].ShipmentDetails_Total = Convert.ToDecimal(dgvList1.Rows[i].Cells["Total"].Value);
                }
                return tracks;
            }
            else
            {
                return null;
            }
        }
        private bool CheckValid()
        {
            if (lblCustomer.Text.Trim().Length == 0)
            {
                lblCustomer.Focus();
                Program.taskbarNotifier.Show(Message.Info, "Chưa chọn nhà khách hàng! Hãy nhập lại.", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                return false;
            }
            if (UISetting.GetDate(mtxShipmentDate.Text) == DateTime.MinValue)
            {
                mtxShipmentDate.Focus();
                Program.taskbarNotifier.Show(Message.Info, "Ngày xuất không hợp lệ! Hãy nhập lại.", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                return false;
            }

            return true;
        }
        private void DisplayFrame()
        {
            UISetting.AddColumn(ref dgvList1, "Item_ID", "Khóa", "", 1, false, true);

            UISetting.AddColumn(ref dgvList1, "RowNumber", "STT", "C", 35, true, true);
            UISetting.AddColumn(ref dgvList1, "Item_Code", "Mã HH", "", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Item_Name", "Tên HH", "", 180, true, true);
            UISetting.AddColumn(ref dgvList1, "CalculationUnit_Name", "ĐVT", "C", 60, true, true);
            UISetting.AddColumn(ref dgvList1, "Quantity", "SL", "C", 45, true, false);
            UISetting.AddColumn(ref dgvList1, "Price", "Đơn giá", "R", 90, true, false);
            UISetting.AddColumn(ref dgvList1, "DownPrice", "Giảm(%)", "R", 60, true, false);

            DataGridViewComboBoxColumn cboColumn = new DataGridViewComboBoxColumn();
            cboColumn.HeaderText = "VAT(%)";
            cboColumn.Name = "VAT";
            cboColumn.Width = 50;
            dgvList1.Columns.Add(cboColumn);
            LoadVAT(ref cboColumn);

            UISetting.AddColumn(ref dgvList1, "Total", "Thành tiền", "R", 95, true, true);

            DataGridViewButtonColumn buttonColumn = new DataGridViewButtonColumn();
            buttonColumn.HeaderText = "Lệnh";
            buttonColumn.Name = "Control";
            buttonColumn.Text = "Xóa";
            buttonColumn.Width = 60;
            buttonColumn.UseColumnTextForButtonValue = true;
            dgvList1.Columns.Add(buttonColumn);

            dgvList1.CellClick += new DataGridViewCellEventHandler(dgvList1_CellClick);
        }
        public void LoadVAT(ref DataGridViewComboBoxColumn box)
        {
            DataTable dt = new DataTable();
            DataColumn dcol = null;
            dcol = new DataColumn("ID", typeof(int));
            dt.Columns.Add(dcol);
            dcol = new DataColumn("NAME", typeof(string));
            dt.Columns.Add(dcol);

            DataRow dr = dt.NewRow();
            dr["ID"] = 0;
            dr["NAME"] = "0";
            dt.Rows.InsertAt(dr, 0);

            dr = dt.NewRow();
            dr["ID"] = 5;
            dr["NAME"] = "5";
            dt.Rows.InsertAt(dr, 1);

            dr = dt.NewRow();
            dr["ID"] = 10;
            dr["NAME"] = "10";
            dt.Rows.InsertAt(dr, 2);

            box.ValueMember = "ID";
            box.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            box.DisplayMember = "NAME";
            box.DataSource = dt;
        }
        void dgvList1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Kiểm tra xóa rows
            if (e.RowIndex < 0 || e.ColumnIndex !=
                    dgvList1.Columns["Control"].Index) return;
            dgvList1.Rows.RemoveAt(e.RowIndex);
            //Tính lại tổng tiền sau khi xóa
            TotalRowsPrice();
            //Sắp xếp lại thứ tự
            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
            }
        }

        private void btnFindItem_Click(object sender, EventArgs e)
        {
            frmStoreStatusList f = new frmStoreStatusList(true);
            f.ShowDialog(this);
            int n = dgvList1.Rows.Count;
            
            if (f.Item_ID > 0)
            {
                //Kiểm tra xem trong danh sách đã có mặt hàng này chưa. Nếu có thì ko cho add nữa
                for (int i = 0; i < n; i++)
                {
                    if (f.Item_ID == Convert.ToInt32(dgvList1.Rows[i].Cells["Item_ID"].Value))
                    {
                        return;
                    }
                }
                //Sau khi kiểm tra xong, nếu được làm tiếp thì sẽ add vào danh sách như sau:
                dgvList1.Rows.Insert(n, 1);
                dgvList1.Rows[n].Cells["RowNumber"].Value = n + 1;
                dgvList1.Rows[n].Cells["Item_ID"].Value = f.Item_ID;
                dgvList1.Rows[n].Cells["Item_Code"].Value = f.Item_Code;
                dgvList1.Rows[n].Cells["Item_Name"].Value = f.Item_Name;
                dgvList1.Rows[n].Cells["CalculationUnit_Name"].Value = f.Unit_Name;

                dgvList1.Rows[n].Cells["Quantity"].Value = 1;
                dgvList1.Rows[n].Cells["DownPrice"].Value = "0.0";
                dgvList1.Rows[n].Cells["VAT"].Value = 10;
                if (cboForms.SelectedIndex == 0)
                {
                    dgvList1.Rows[n].Cells["Price"].Value = f.Item_WholesalePrice.ToString("N1");
                    dgvList1.Rows[n].Cells["Total"].Value = f.Item_WholesalePrice.ToString("N1");
                }
                else
                {
                    dgvList1.Rows[n].Cells["Price"].Value = f.Item_RetailPrice.ToString("N1");
                    dgvList1.Rows[n].Cells["Total"].Value = f.Item_RetailPrice.ToString("N1");
                }

                // Cho sửa chữa dữ liệu trên datagridview tại các ô của cột Quantity, Price, DownPrice, VAT
                dgvList1.BeginEdit(false);
                dgvList1.CurrentCell = dgvList1.Rows[n].Cells["Quantity"];
                TotalRowsPrice();
                dgvList1.BeginEdit(true);
                
            }
        }
        private void TotalRowsPrice()
        {
            decimal totalPrice=0, totalDownPrice=0, totalVAT=0, Total = 0;
            Total = Convert.ToDecimal(txtRemaining.Text);
            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                totalPrice += Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["Quantity"].Value);
                totalDownPrice += Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value)*Convert.ToDecimal(dgvList1.Rows[i].Cells["DownPrice"].Value)/100;
                totalVAT += (Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["Quantity"].Value) -
                    Convert.ToDecimal(dgvList1.Rows[i].Cells["Price"].Value) * Convert.ToDecimal(dgvList1.Rows[i].Cells["DownPrice"].Value) / 100) *
                    Convert.ToDecimal(dgvList1.Rows[i].Cells["VAT"].Value) / 100;
                Total += Convert.ToDecimal(dgvList1.Rows[i].Cells["Total"].Value);
            }
            txtTotalPrice.Text = totalPrice.ToString("N1");
            txtTotalDownPrice.Text = totalDownPrice.ToString("N1");
            txtTotalVAT.Text = totalVAT.ToString("N1");
            txtTotal.Text = Total.ToString("N1");
            if (dgvList1.Rows.Count > 0)
            {
                cboForms.Visible = false;
                lblForms.Visible = true;
            }
            else
            {
                cboForms.Visible = true;
                lblForms.Visible = false;
            }
        }
        private decimal TotalColomnPrice(decimal price, int quantity, decimal downprice, decimal vat)
        {
            decimal giam, thue, gia_sau_khi_giam, total; ;

            giam = price * downprice / 100;
            gia_sau_khi_giam = price - giam;
            thue = gia_sau_khi_giam * vat / 100;
            
            total = (gia_sau_khi_giam + thue)*quantity;
            return total;
        }

        private void dgvList1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            int newInteger;
            decimal newDecimal;
            DataTable _dt = InventoryDB.GetQuantityByItem(Convert.ToInt32(dgvList1.Rows[e.RowIndex].Cells["Item_ID"].Value)).Tables[0];
            if (e.ColumnIndex == dgvList1.Columns["Quantity"].Index)
            {
                if (!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0)
                {
                    e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "Số lượng phải là số nguyên dương", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }

                else if (newInteger > Convert.ToInt32(_dt.Rows[0]["Quantity"]))
                {
                   // e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "Mã: " + 
                        " ''" + dgvList1.Rows[e.RowIndex].Cells["Item_Code"].Value +
                        "'' chỉ còn " + _dt.Rows[0]["Quantity"].ToString()+ 
                        " " + dgvList1.Rows[e.RowIndex].Cells["CalculationUnit_Name"].Value +
                        ". Đề nghị nhập thêm." , UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }
            }
            if (e.ColumnIndex == dgvList1.Columns["Price"].Index)
            {
                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "Đơn giá phải là số dương", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }
            }
            if (e.ColumnIndex == dgvList1.Columns["DownPrice"].Index)
            {
                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "Giảm giá phải là số dương", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }

            }
            if (e.ColumnIndex == dgvList1.Columns["VAT"].Index)
            {
                
                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "VAT phải là số dương", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }
            }
            
        }
        private void dgvList1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int quantity;
            decimal price, downprice, vat, total;
            quantity = Convert.ToInt32(dgvList1.Rows[e.RowIndex].Cells["Quantity"].Value);
            price = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Price"].Value);
            downprice = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["DownPrice"].Value);
            vat = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["VAT"].Value);

            total = TotalColomnPrice(price, quantity, downprice, vat);

            dgvList1.Rows[e.RowIndex].Cells["Total"].Value = total.ToString("N1");

            TotalRowsPrice();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValid())
                return;
            FormToInfo();
            ShipmentDetailsInfo[] tracks = ReadShipmentDetails();
            if (tracks == null)
            {
                Program.taskbarNotifier.Show(Message.Info, "Chưa có mặt hàng nào được nhập! Hãy nhập lại.", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                return;
            }
            if (Shipmentinf.Shipment_ID > 0)
            {
                if (ShipmentDB.Update(Shipmentinf))
                {
                    ShipmentDetailsDB.Delete(Shipmentinf.Shipment_ID);
                    
                    for (int i = 0; i < tracks.Length; i++)
                    {
                        tracks[i].ShipmentDetails_ShipmentID = Shipmentinf.Shipment_ID;
                        if (ShipmentDetailsDB.Insert(tracks[i]) > 0)
                        {
                            Program.taskbarNotifier.Show(Message.Info, Message.Update_Complete, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                            dlgResult = DialogResult.OK;
                        }
                        else
                            Program.taskbarNotifier.Show(Message.Info, Message.Update_Error, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                    }

                }
                else
                    Program.taskbarNotifier.Show(Message.Info, Message.Update_Error, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
            }
            else
            {
                Shipmentinf.Shipment_ID = ShipmentDB.Insert(Shipmentinf);
                if (Shipmentinf.Shipment_ID > 0)
                {
                    ShipmentDetailsDB.Delete(Shipmentinf.Shipment_ID);
                    for (int i = 0; i < tracks.Length; i++)
                    {
                        tracks[i].ShipmentDetails_ShipmentID = Shipmentinf.Shipment_ID;
                        if (ShipmentDetailsDB.Insert(tracks[i]) > 0)
                        {
                            Program.taskbarNotifier.Show(Message.Info, Message.Create_Complete, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                            dlgResult = DialogResult.OK;
                        }
                        else
                            Program.taskbarNotifier.Show(Message.Info, Message.Create_Error, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                    }
                }
                else
                    Program.taskbarNotifier.Show(Message.Info, Message.Create_Error, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
            }

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (Shipmentinf.Shipment_ID > 0)
            {
                frmReport f = new frmReport("PHIEU XUAT HANG", new string[] {Shipmentinf.Shipment_ID.ToString(),"Phiếu xuất hàng"});
                f.Show();
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmShipment_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Shipmentinf.Shipment_ID = 0;
            lblNo.Text = UISetting.AutoFillShipmentCode();
            mtxShipmentDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            lblCustomer.Text = "???";
            lblCustomer.Tag = 0;
            txtReceive.Text = "";
            cboForms.SelectedIndex = 0;
            dgvList1.Rows.Clear();
            TotalRowsPrice();
        }

        private void frmShipment_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control && !dgvList1.Focused)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.Escape:
                    this.Dispose();
                    this.DialogResult = dlgResult;
                    this.Close();
                    break;
            }
        }

        private void dgvList1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvList1.Columns["Price"].Index || e.ColumnIndex == dgvList1.Columns["DownPrice"].Index)
            {
                decimal d = decimal.Parse(e.Value.ToString());
                e.Value = d.ToString("N1");
            }
        }

        private void btnFindCustomer_Click(object sender, EventArgs e)
        {
            frmCustomerList f = new frmCustomerList(true);
            f.ShowDialog(this);
            if (Convert.ToInt32(f.Customer_ID) > 0)
            {
                lblCustomer.Tag = Convert.ToInt32(f.Customer_ID);
                lblCustomer.Text = f.Customer_Name.ToUpper();
                txtRemaining.Text = Convert.ToDecimal(f.Customer_Remaining).ToString("N1");
                TotalRowsPrice();
            }
        }

        private void cboForms_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblForms.Text = cboForms.Text;
            
        }

        private void btnNewIncome_Click(object sender, EventArgs e)
        {
            if (Shipmentinf.Shipment_ID > 0)
            {
                Form fS = new frmIncome(0);
                fS.ShowDialog();
            }
        }


    }
}